package com.shy.example.alibaba.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("config")
@Slf4j
@RefreshScope
public class ConfigController {
    @Value("${config.info}")
    private String configInfo;
    @Value("${config.version}")
    private String configVersion;

    @GetMapping("info")
    @SentinelResource(value = "configInfo", blockHandler = "blockHandler")
    public String getInfo(){
        log.info("访问服务成功-----getInfo: " + configInfo);
        return configInfo;
    }

    @GetMapping("version")
    @SentinelResource("configVersion")
    public String getVersion(){
        initFlowRules();
        log.info("访问服务成功------getVersion: " + configVersion);
        return configVersion;
    }

    public String blockHandler(BlockException exception){
        log.warn(Thread.currentThread().getName() + " 本网站提醒您，getInfo服务访问失败！你已经被限流，请稍后再试");
        return "本网站提醒您，getInfo服务访问失败！你已被限流，请稍后再试";
    }

    @PostConstruct
    private  void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setRefResource("configInfo");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(2);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
